<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\AutoTag\Listener;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Corp\Contract\CorpContract;
use MoChat\App\WorkContact\Contract\WorkContactContract;
use MoChat\App\WorkContact\Contract\WorkContactEmployeeContract;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\App\WorkRoom\Event\CreateRoomMemberEvent;
use MoChat\Plugin\AutoTag\Action\Dashboard\Traits\AutoContactTag;
use MoChat\Plugin\AutoTag\Contract\AutoTagContract;
use MoChat\Plugin\AutoTag\Contract\AutoTagRecordContract;
use Psr\Container\ContainerInterface;

/**
 * 客户群创建事件
 * 有新增客户群时，回调该事件。收到该事件后，企业可以调用获取客户群详情接口获取客户群详情。
 * @Listener
 */
class CreateRoomMemberListener implements ListenerInterface
{
    use AutoContactTag;

    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var CorpContract
     */
    protected $corpService;

    /**
     * @var AutoTagContract
     */
    protected $autoTagService;

    /**
     * @var AutoTagRecordContract
     */
    protected $autoTagRecordService;

    /**
     * @var WorkEmployeeContract
     */
    protected $workEmployeeService;

    /**
     * @var WorkContactEmployeeContract
     */
    protected $workContactEmployeeService;

    /**
     * @var WorkContactContract
     */
    protected $workContactService;

    /**
     * @var StdoutLoggerInterface
     */
    private $logger;

    public function listen(): array
    {
        return [
            CreateRoomMemberEvent::class,
        ];
    }

    /**
     * @param CreateRoomMemberEvent $event
     */
    public function process(object $event)
    {
        try {
            $message = $event->message;
            $this->logger = $this->container->get(StdoutLoggerInterface::class);
            $this->workEmployeeService = $this->container->get(WorkEmployeeContract::class);
            $this->workContactService = $this->container->get(WorkContactContract::class);
            $this->workContactEmployeeService = $this->container->get(WorkContactEmployeeContract::class);
            $this->autoTagService = $this->container->get(AutoTagContract::class);
            $this->autoTagRecordService = $this->container->get(AutoTagRecordContract::class);

            $this->logger->info(sprintf('[自动打标签]客户入群行为打标签开始'));

            $corpId = $message['corpId'];
            $rooms = $message['rooms'];

            if (empty($rooms)) {
                return [];
            }
            $autoTag = $this->autoTagService->getAutoTagByTypeOnOff(2, 1, ['id', 'tag_rule', 'corp_id']);
            if (empty($autoTag)) {
                return [];
            }
            foreach ($autoTag as $auto) {
                // 2 客户入群群聊id
                foreach ($rooms as $item) {
                    // 客户0跳出循环
                    $contactId = (int) $item['contact_id'];
                    if ($contactId === 0) {
                        continue;
                    }
                    if (empty($auto['tagRule'])) {
                        continue;
                    }
                    foreach (json_decode($auto['tagRule'], true, 512, JSON_THROW_ON_ERROR) as $key => $tagRule) {
                        if (empty($tagRule) || empty($tagRule['rooms'])) {
                            continue;
                        }
                        $room_ids = array_column($tagRule['rooms'], 'id');
                        $tags = $tagRule['tags'];
                        // 空标签跳出循环
                        if (empty($tags)) {
                            continue;
                        }
                        if (in_array((int) $item['room_id'], $room_ids, true)) {
                            $data = ['contactId' => 0, 'employeeId' => 0, 'tagArr' => array_column($tags, 'tagid'), 'employeeWxUserId' => '', 'contactWxExternalUserid' => ''];
                            // 客户id
                            $data['contactId'] = $contactId;
                            // 员工id
                            $contactEmployee = $this->workContactEmployeeService->getWorkContactEmployeeByCorpIdContactId($contactId, $auto['corpId'], ['employee_id']);
                            if (empty($contactEmployee) || empty($contactEmployee['employeeId'])) {
                                continue;
                            }
                            $data['employeeId'] = $contactEmployee['employeeId'];
                            // 客户
                            $contact = $this->workContactService->getWorkContactById($contactId, ['wx_external_userid']);
                            $data['contactWxExternalUserid'] = $contact['wxExternalUserid'];
                            // 员工
                            $employee = $this->workEmployeeService->getWorkEmployeeById($contactEmployee['employeeId'], ['wx_user_id']);
                            if (empty($employee)) {
                                continue;
                            }
                            $data['employeeWxUserId'] = $employee['wxUserId'];
                            $data['corpId'] = $auto['corpId'];
                            $this->autoTag($data);
                            // 数据库操作
                            $record = $this->autoTagRecordService->getAutoTagRecordByCorpIdWxExternalUseridAutoTagId($auto['corpId'], $data['contactWxExternalUserid'], $auto['id'], $key + 1, ['id', 'trigger_count']);
                            $trigger_count = empty($record) ? 1 : $record['triggerCount'] + 1;
                            $createMonitors = [
                                'auto_tag_id' => $auto['id'],
                                'contact_id' => $contactId,
                                'tag_rule_id' => $key + 1,
                                'wx_external_userid' => $data['contactWxExternalUserid'],
                                'employee_id' => $data['employeeId'],
                                'contact_room_id' => $item['room_id'],
                                'tags' => Json::encode(array_column($tags, 'tagname'), JSON_THROW_ON_ERROR),
                                'corp_id' => $auto['corpId'],
                                'trigger_count' => $trigger_count,
                                'status' => 1,
                                'created_at' => date('Y-m-d H:i:s'),
                            ];
                            if (empty($record)) {
                                $this->autoTagRecordService->createAutoTagRecord($createMonitors);
                            } else {
                                $this->autoTagRecordService->updateAutoTagRecordById($record['id'], $createMonitors);
                            }
                        }
                    }
                }
            }
        } catch (\Throwable $e) {
            $this->logger->error(sprintf('[自动打标签]客户入群行为打标签失败，错误信息: %s', $e->getMessage()));
            $this->logger->error($e->getTraceAsString());
        }
    }
}
